package main;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import captchas.CaptchasDotNet;
import DBClasses.User;

@SuppressWarnings("serial")
public class Registration extends BaseServlet
{
	@SuppressWarnings({ "unused", "unchecked", "rawtypes" })
	@Override
	protected void action(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException
	{
		external.error_msg = "";
		String[] mass = { "pswrd", "pswrd2", "login", "name", "sname", "email",
				"sex" };
		String ptrn = req.getParameter("ptrnm");
		Map<String, String> values = new HashMap<String, String>();
		boolean isError = false;
		for (String string : mass)
			values.put(string, req.getParameter(string));
		String pass1 = values.get("pswrd");
		String pass2 = values.get("pswrd2");
		Iterator iter = values.entrySet().iterator();
		while (iter.hasNext())
		{
			Map.Entry<String, String> entry = (Map.Entry<String, String>) iter
					.next();
			if (entry.getValue() == null || entry.getValue().equals(""))
			{
				external.error_msg = "Введите все обязательные поля!";
				isError = true;
				break;
			}
		}
		if (pass1 != null && pass2 != null && !pass1.equals(pass2))
		{
			external.error_msg = "Пароли не совпадают!";
			isError = true;
		}
		PersistenceManager manager = PMF.get().getPersistenceManager();
		List<User> users = (List<User>) manager.newQuery(
				"select from " + User.class.getName() + " where login == '"
						+ values.get("login") + "'").execute();
		if (users.size() > 0)
		{
			external.error_msg = "Такой логин занят";
			isError = true;
		}
		users = (List<User>) manager.newQuery(
				"select from " + User.class.getName() + " where _mail == '"
						+ values.get("email") + "'").execute();
		if (users.size() > 0)
		{
			external.error_msg = "Пользователь с тамим e-mail ужу зарегистрирован!";
			isError = true;
		}
		CaptchasDotNet captchas = new captchas.CaptchasDotNet(
				req.getSession(true), // Ensure session
				"demo", // client
				"secret" // secret
		);
		String password = req.getParameter("captcha");
		switch (captchas.check(password)) {
		case 's':
		case 'm':
		case 'w':
			external.error_msg = "Неверные данные с капчи!";
			isError = true;
			break;
		}
		if (isError)
		{
			RequestDispatcher disp = req.getRequestDispatcher("reg.jsp");
			disp.forward(req, resp);
		} else
		{
			User user = new User(values.get("login"), pass1,
					values.get("name"), values.get("sname"),
					values.get("email"), values.get("sex").toString()
							.equals("Male"));
			if (values.get("login").equals("root"))
			{
				user.setNewsAccess(true);
				user.setShopAccess(true);
			}

			manager.makePersistent(user);
			manager.close();
			resp.sendRedirect("/index.jsp");
		}
	}
}
